package com.flydust.apipulse.service;

import com.flydust.apipulse.entity.Project;
import com.flydust.apipulse.entity.Directory;
import com.flydust.apipulse.repository.ProjectRepository;
import com.flydust.apipulse.service.DirectoryService; // 添加缺失的导入语句
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class ProjectService {

    @Autowired
    private ProjectRepository projectRepository;
    
    @Autowired
    private DirectoryService directoryService;

    public List<Project> findAll() {
        return projectRepository.findAll();
    }

    public List<Project> findAllWithEndpointCount() {
        List<Object[]> results = projectRepository.findAllWithEndpointCount();
        return results.stream().map(result -> {
            Project project = (Project) result[0];
            Long count = (Long) result[1];
            project.setEndpointCount(count.intValue());
            return project;
        }).collect(Collectors.toList());
    }

    public Optional<Project> findById(Long id) {
        return projectRepository.findById(id);
    }

    public Project save(Project project) {
        Project savedProject = projectRepository.save(project);
        
        // 如果是新项目，创建默认目录
        if (project.getId() == null) {
            Directory defaultDirectory = new Directory("默认", savedProject.getId());
            directoryService.save(defaultDirectory);
        }
        
        return savedProject;
    }

    public void deleteById(Long id) {
        projectRepository.deleteById(id);
    }
}